WORK_DIR=/data/build
mkdir -p $WORK_DIR
cd $WORK_DIR

# 下载 nginx 源码
NGINX_VER=$(nginx -v 2>&1 | cut -d' '  -f3 | cut -d'/' -f2)
wget https://github.91chi.fun/https://github.com/nginx/nginx/archive/refs/tags/release-${NGINX_VER}.zip
unzip release-${NGINX_VER}.zip
cd nginx-release-${NGINX_VER}

# 下载 dav module 源码
wget https://github.91chi.fun/https://github.com/arut/nginx-dav-ext-module/archive/refs/heads/master.zip
unzip master.zip
rm master.zip

# 下载 headers more
wget https://github.91chi.fun/https://github.com/openresty/headers-more-nginx-module/archive/refs/heads/master.zip
unzip master.zip
rm master.zip

# 获取构建参数
get_nginx_build_args() {
	nginx -V 2>&1 | tail -n 1 | xargs -n1 | grep -v 'add-dynamic-module' | tail -n +3 | while read line; do
		echo "$line" | grep -q '=.* '
		if [ $? -eq 0 ];then
			ARG=$(echo $line | sed "s/\=/\=\'/")
			echo "\"${ARG}'\""
		else
			echo "$line"
		fi
	done
}
BUILD_ARGS=$(get_nginx_build_args | xargs)

# 安装依赖包
sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
apk update
APPS='gcc autoconf make musl-dev linux-headers pcre-dev openssl-dev zlib-dev libxml2-dev libxslt-dev'
apk add $APPS

# 构建
eval "./auto/configure --with-http_dav_module --add-module=$PWD/nginx-dav-ext-module-master --add-module=$PWD/headers-more-nginx-module-master $BUILD_ARGS"
make -j4
DST=objs/nginx
strip $DST

# 安装
cp $DST $(which nginx)
apk add apache2-utils # 用于密码管理

# 清理
cd /tmp
rm -rf $WORK_DIR
apk del --purge $APPS
rm -r /usr/lib/nginx/modules/
rm -r /etc/nginx/modules
rm -rf /var/cache/apk
